// 触发副作用函数
function trigger(target, key, type, newVal) {
  // 从桶里拿出来与target相关的依赖集合
  const depsMap = bucket.get(target)
  if (!depsMap) return
  // 找到与当前key相关的副作用函数们
  const effects = depsMap.get(key)
  // 声明一个Set结构的集合
  const effectsToRun = new Set()
  // 将与key相关的副作用函数们添加进effectsToRun
  effects &&
    effects.forEach((effectFn) => {
      if (effectFn !== activeEffect) {
        effectsToRun.add(effectFn)
      }
    })
  if (type === 'ADD' && Array.isArray(target)) {
    const lengthEffects = depsMap.get('length')
    lengthEffects &&
      lengthEffects.forEach((effectFn) => {
        if (effectFn !== activeEffect) {
          effectsToRun.add(effectFn)
        }
      })
  }
  if (Array.isArray(target) && key === 'length') {
    depsMap.forEach((effects, key) => {
      if (key >= newVal) {
        effects.forEach((effectFn) => {
          if (effectFn !== activeEffect) {
            effectsToRun.add(effectFn)
          }
        })
      }
    })
  }
  if (
    type === TriggerType.ADD ||
    type === TriggerType.DELETE ||
    (type === 'SET' &&
      Object.prototype.toString.call(target) === '[object Map]')
  ) {
    const iterateEffects = depsMap.get(ITERATE_KEY)
    // 将与ITERATE_KEY相关的副作用函数们添加进effectsToRun
    iterateEffects &&
      iterateEffects.forEach((effectFn) => {
        if (effectFn !== activeEffect) {
          effectsToRun.add(effectFn)
        }
      })
  }

  if (
    (type === TriggerType.ADD ||
    type === TriggerType.DELETE) &&
    Object.prototype.toString.call(target) === '[object Map]'
  ) {
    const iterateEffects = depsMap.get(MAP_KEY_ITERATE_KEY)
    // 将与ITERATE_KEY相关的副作用函数们添加进effectsToRun
    iterateEffects &&
      iterateEffects.forEach((effectFn) => {
        if (effectFn !== activeEffect) {
          effectsToRun.add(effectFn)
        }
      })
  }

  effectsToRun.forEach((effectFn) => {
    // 如果一个副作用函数有调度器，那么优先调用该调度器，并将副作用函数作为参数传递
    if (effectFn.options.scheduler) {
      effectFn.options.scheduler(effectFn)
    } else {
      // 否则直接执行副作用函数，默认行为
      effectFn()
    }
  })
}
